package com.card.user;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com.card.message.JsonMessageCenter;
import com.xiaoao.net.json.message.JsonMessage;
import com.xiaoao.net.utils.StringUtil;

/**
 * 用户管理器
 * @author xiaoaogame
 */
public class UserManager {
	private static UserManager instance = new UserManager();
	public static UserManager getInstance() {
		return instance;
	}
	//当前所有在线玩家
	public Map<String,User> userMap = new ConcurrentHashMap<>();
	
	/**
	 * 删除玩家信息
	 * @param user
	 */
	public void removeUser(User user) {
		userMap.remove(user.getPrimaryKey());
	}
	/**
	 * 根据主键获取在线用户
	 * @param primaryKey
	 * @return
	 */
	public User getUserByKey(String primaryKey) {
		if(StringUtil.NullOrEmpty(primaryKey)) {
			return null;
		}
		return userMap.get(primaryKey);
	}
	
	/**
	 * 添加在线用户
	 * @param user
	 */
	public void addUser(User user) {
		userMap.put(user.getPrimaryKey(), user);
	}
	
	
	public Map<String, User> getUserMap() {
		return userMap;
	}
	/**
	 * 广播给大厅里的人
	 * @param serverMsg
	 */
	public void broadMessage(JsonMessage serverMsg) {
		//循环
		broadMessage(serverMsg, null);
	}
	public void broadMessage(JsonMessage serverMsg,final String prohibitUserId) {
		for(User user : userMap.values()){
			JsonMessageCenter.getInstance().sendMessage(serverMsg, user.getCtx());
		}
	}
	public void broadMessageOutRoom(JsonMessage serverMsg) {
		for(User user : userMap.values()){
			if(user.getRoom() == null) {
				JsonMessageCenter.getInstance().sendMessage(serverMsg, user.getCtx());
			}
		}
	}
	
	public void addDownShareGold(String userId) {
		User user = UserUtils.getUserByPrimaryKey(userId);
		if(user != null) {
			user.userStatistics().addDownShare();
			user.sendUserUpdateMessage();
		}
	}
}
